import * as THREE from 'three';

function getGeometry({ data }: ImageData) {
  const group = new THREE.Group();
  for (let i = 0; i <= 15; i++) {
    for (let j = 0; j <= 15; j++) {
      let start = i * 4 + j * 4 * 16;
      const r = data[start],
        g = data[start + 1],
        b = data[start + 2],
        a = data[start + 3];

      if (r === g && g === b && b === r) continue;

      if (a != 0) {
        const block = new THREE.BoxGeometry(1, 1, 1),
          material = new THREE.MeshBasicMaterial({ color: new THREE.Color(`rgb(${r},${g},${b})`) }),
          cube = new THREE.Mesh(block, material);

        cube.position.set(i - 7, j, 0);
        group.add(cube);
      }
    }
  }
  group.rotateY(Math.PI);
  return group;
}

export default function (src: string) {
  return new Promise<[THREE.Group]>((res, rej) => {
    const img = document.createElement('img');
    img.src = src;

    img.addEventListener('load', () => {
      const canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d')!;
      ctx.drawImage(img, 0, 0, 16, 16);
      ctx.rotate(Math.PI * 0.5);

      const imgData = ctx.getImageData(0, 0, 16, 16);

      res([getGeometry(imgData)]);
    });

    img.addEventListener('error', e => {
      rej(e);
    });
  });
}
